<?php
namespace Admin\Controller;
Use Think\Controller;

    class PublicController extends EmptyController
    {
        //初始化的方法
        public function _initialize()
        {
            //判断session是否存在
    		if(empty($_SESSION['admin_user'])){
    			//跳转到 登陆页
    			$this->redirect("Login/login");
    		}
            // v($_SESSION);
            $where['user_id'] = $_SESSION['admin_user']['id'];

            $list = M('role')->field('model,fun')->where('id in'.M('actor_role')->field('role_id')->where('actor_id in'.M('user_actor')->field('actor_id')->where($where)->buildSql())->buildSql())->select();

            //控制器名转换为大写
    		foreach ($list as $key => $val) {
    			$list[$key]['model'] = ucfirst($val['model']);
    		}

            //查看查询出来的信息
            // v($list); exit;

            $rolelist = array();
            //遍历重新拼装
            $rolelist['Index'] = array('index');
            $rolelist['User'] = array('index');
            foreach($list as $v){
                $rolelist[$v['model']][] = $v['fun'];
                //把修改和执行修改 添加和执行添加 拼装到一起
                if($v['fun']=="edit"){
                    $rolelist[$v['model']][]="update";
                }
                if($v['fun']=="add"){
                    $rolelist[$v['model']][]="insert";
                }
            }

            //将权限信息放置到session中
            $_SESSION['admin_user']['rolelist'] = $rolelist;

            //重组的信息
    		// V($_SESSION);exit;

            // 权限过滤
            $model = CONTROLLER_NAME; //获取控制器名
            $fun = ACTION_NAME; //获取方法名

            // echo $model.'/'.$fun;

            $rolelist = $_SESSION['admin_user']['rolelist']; //获取权限列表
            // v($rolelist);
            // V($_SESSION);exit;
            //让超级管理员admin拥有所有权限
            if($_SESSION['admin_user']['name'] != 'admin'){
                //验证操作权限
                if(empty($rolelist[$model]) || !in_array($fun,$rolelist[$model])){
                    $this->error("抱歉！没有操作权限！");
                    exit;
                }

            }

        }

        //不存在方法跳转404
        public function _empty()
        {
            $this->display('Notfound/index');
        }
    }
